package data;

import java.util.UUID;

import modele.ObjetSimple;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class BaseConverter implements Converter {
	
    @SuppressWarnings("rawtypes")
	@Override
    public boolean canConvert(Class clazz) {
        return clazz.equals(ObjetSimple.class);
    }
    
    @Override
    public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
        ObjetSimple BaseModele = (ObjetSimple) value;
        
        // ID
        writer.startNode("id");
        writer.setValue(BaseModele.getId().toString());
        writer.endNode();
        
        // Nom
        writer.startNode("nom");
        writer.setValue(BaseModele.getNom());
        writer.endNode();
        
        // URL
        writer.startNode("url");
        writer.setValue(BaseModele.getUrl());
        writer.endNode();
    }
    
    @Override
    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
        // ID
        reader.moveDown();
        String id = reader.getValue();
        reader.moveUp();
        
        // Nom
        reader.moveDown();
        String nom = reader.getValue();
        reader.moveUp();
        
        // URL
        String url = "";
        if (reader.hasMoreChildren()) {
	        reader.moveDown();
	        url = reader.getValue();
	        reader.moveUp();
        }
        
        ObjetSimple o = new ObjetSimple(UUID.fromString(id), nom);
        o.setUrl(url);
        return o;
    }
}
